﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BYFW.WebBase;
using BYFW.DAL;
using System.Web.UI;
using BYFW.SFL;
using BYFW.BOL;
using System.Text.RegularExpressions;
using System.IO;
using BYFW.Encrypt;
using System.Web.UI.WebControls;
using System.Web.Configuration;

namespace LDSP.BRL
{
    public class BasePage : BYFW.WebBase.BasePage
    {
        protected override void OnInit(EventArgs e)
        {
            try
            {
                base.OnInit(e);
                this.RedirectBefore();
                g_pageInfo = PageInfo.GetPageInfo(this);
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        public static object s_lock = new object();

        protected bool needCachePageInfo = false;

        protected PageInfo g_pageInfo = null;

        protected IDBOP DefaultDB
        {
            get { return new BaseEntity().DB; }
        }

        public SystemUser LoginAdmin
        {
            get
            {
                return this.Session["LoginAdmin"] as SystemUser;
            }
            set
            {
                this.Session["LoginAdmin"] = value;
            }
        }

        public EnterpriseUser LoginUser
        {
            get
            {
                return this.Session["LoginUser"] as EnterpriseUser;
            }
            set
            {
                this.Session["LoginUser"] = value;
            }
        }

        public LoginLog LoginLog
        {
            get
            {
                return this.Session["LoginLog"] as LoginLog;
            }
            set
            {
                this.Session["LoginLog"] = value;
            }
        }
        

        /// <summary>
        /// 本项目默认的updatepanel
        /// </summary>
        public override UpdatePanel ScriptPanel
        {
            get
            {
                Control ctrl = this.FindControl("pnl_script");
                if (ctrl is UpdatePanel)
                    return (UpdatePanel)ctrl;
                else
                    return null;
            }
        }

        /// <summary>
        /// 获取数据中的数字，默认为0
        /// </summary>
        /// <param name="origin"></param>
        /// <returns></returns>
        public int GetInt(object origin)
        {
            if (origin == null)
            {
                return 0;
            }
            return CommonOP.GetInt(origin.ToString(), false);
        }
        /// <summary>
        /// 获取数字字符串为数字，默认为0
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public double GetDouble(object origin)
        {
            if (origin == null)
            {
                return 0;
            }
            return CommonOP.GetDouble(origin.ToString(), false);
        }
        /// <summary>
        /// 截断长字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public string Ellipsis(string origin, int length)
        {
            return CommonOP.Ellipsis(origin, length);
        }
        /// <summary>
        /// 检查输入的字符长度
        /// </summary>
        /// <param name="name">字段名称</param>
        /// <param name="str">字段值</param>
        /// <param name="length">最大长度</param>
        public void CheckLength(string name, string str, int length)
        {
            if (System.Text.Encoding.ASCII.GetByteCount(str) > length)
            {
                throw new CustomException(string.Format("【{0}】最多输入{1}个字符", name, length));
            }
        }
        /// <summary>
        /// 输入的字符串是否是符合适合用作名字：只包含字母，数字以及下划线和-
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public bool IsName(string input)
        {
            string pat = @"^[()\[\]0-9A-Za-z_\-\u4e00-\u9fa5]+$";
            Regex reg = new Regex(pat);
            return reg.IsMatch(input);
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userPwd"></param>
        /// <param name="validateCode"></param>
        /// <returns></returns>
        protected bool Login(string userName, string userPwd, string validateCode, int enterpriseID)
        {
            if (this.Session["ValidateImg"] == null)
            {
                this.JSAlert("当前页面已过期！");
                return false;
            }
            string vcode = this.Session["ValidateImg"].ToString().ToLower();
            if (validateCode.Trim().ToLower() != vcode)
            {
                this.JSAlert("验证码输入错误！");
                return false;
            }
            string superUser = System.Configuration.ConfigurationManager.AppSettings["user"];
            string superPwd = System.Configuration.ConfigurationManager.AppSettings["pwd"];
            if (enterpriseID == 0)
            {
                SystemUser su = new SystemUser();
                su.GetProperties(userName);
                if (su.Password == userPwd)
                {
                    LoginAdmin = su;
                    LoginUser = null;
                    return true;
                }
                else if (superUser.ToLower() == userName.Trim().ToLower() && superPwd == userPwd)
                {
                    LoginAdmin = new SystemUser();
                    LoginAdmin.IsSuper = true;
                    LoginAdmin.Name = "超级管理员";
                    LoginAdmin.Password = superPwd;
                    LoginUser = null;
                    return true;
                }
                else
                {
                    this.JSAlert("用户名或密码错误！");
                }
            }
            else
            {
                EnterpriseUser eu = new EnterpriseUser();
                eu.GetProperties(userName);
                if (eu.Password == userPwd)
                {
                    if (eu.IsValid)
                    {
                        LoginUser = eu;
                        LoginAdmin = null;
                        LoginLog = new LoginLog();
                        LoginLog.EnterpriseUserID = LoginUser.ID;
                        LoginLog.LoginIP = this.GetUserIP();
                        LoginLog.Add();
                        return true;
                    }
                    else
                    {
                        this.JSAlert("用户已失效，请与系统管理员联系！");
                    }
                }
                else
                {
                    this.JSAlert("用户名或密码错误！");
                }
            }
            return false;
        }

        /// <summary>
        /// 根据用户判断并进行页面跳转
        /// </summary>
        public override void RedirectBefore()
        {
            if (this.LoginUser == null)
            {
                this.GoToLogin();
            }
        }
        /// <summary>
        /// 跳转到登录页
        /// </summary>
        public virtual void GoToLogin()
        {
            //this.JSRedirect(this.BU + "/Login.aspx", true, true);
            this.Response.Redirect("~/UI/login.aspx", true);
        }
        /// <summary>
        /// 登出
        /// </summary>
        public virtual void Logout()
        {
            this.LoginAdmin = null;
            this.LoginUser = null;
            if (LoginLog != null)
            {
                LoginLog.LogoutDT = DateTime.Now;
                LoginLog.Update();
            }
            this.GoToLogin();
        }
        /// <summary>
        /// 列表显示页面，初始化页面的过滤条件控件
        /// </summary>
        public void JSInitFilterControls()
        {
            this.JS(@"$(function(){initFilterControls();})");
        }
        /// <summary>
        /// 设置页面日期文本框就只读
        /// </summary>
        /// <param name="clientID"></param>
        public void JSSetDateTimeReadOnly(string clientID)
        {
            this.JS(string.Format("setReadOnly('{0}')", clientID));
        }
        /// <summary>
        /// 页面上获取组合条件
        /// </summary>
        /// <param name="originCond"></param>
        /// <param name="appendCond"></param>
        /// <param name="isAnd"></param>
        /// <returns></returns>
        protected string AppendCondition(string originCond, string appendCond, bool isAnd)
        {
            return originCond == "" ? appendCond : ("(" + originCond + (isAnd ? " and " : " or ") + appendCond + ")");
        }

        /// <summary>
        /// 页面上获取组合条件（适用多字段全文的模糊与匹配）
        /// </summary>
        /// <param name="originCond"></param>
        /// <param name="keywords"></param>
        /// <param name="displayFieldNames"></param>
        /// <returns></returns>
        protected string AppendConditionMulti(string originCond, string keywords, params string[] displayFieldNames)
        {
            string res = "";
            for (int i = 0; i < displayFieldNames.Length; i++)
            {
                if (!string.IsNullOrEmpty(displayFieldNames[i]))
                {
                    res = this.AppendCondition(res, DefaultDB.GetSQLMultiCondition(displayFieldNames[i], EDataType.String, keywords, true, true), false);
                }
            }
            return this.AppendCondition(originCond, res, true);
        }
        /// <summary>
        /// 获取gird中选中的项，并传入执行委托
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="grid"></param>
        /// <param name="checkboxID"></param>
        /// <param name="action"></param>
        protected void DoGirdChecked<T>(GridView grid, string checkboxID, Action<T> action) where T : BaseEntity, new()
        {
            for (int i = 0; i <= grid.Rows.Count - 1; i++)
            {
                CheckBox chb = (CheckBox)grid.Rows[i].FindControl(checkboxID);
                if (chb.Checked)
                {
                    T ett = new T();
                    ett.GetProperties(this.GetInt(grid.DataKeys[i].Value));
                    action(ett);
                }
            }
        }
        /// <summary>
        /// 删除Grid中选中的记录
        /// </summary>
        protected void DeleteCheckedInGrid<T>(GridView grid) where T : BaseEntity, new()
        {
            DoGirdChecked<T>(grid, "chb", delegate(T ett)
            {
                ett.Delete();
            });
        }

        /// <summary>
        /// 是否能下载
        /// </summary>
        /// <param name="codification"></param>
        /// <param name="showMessage"></param>
        /// <returns></returns>
        protected bool CanDownload(Codification codification, bool showMessage=true)
        {
            if (codification.FileName == "" || !File.Exists(codification.GetDownloadFileFullName()))
            {
                if (showMessage)
                {
                    this.JSAlert("文件不存在！");
                }
                return false;
            }
            return true;
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="context"></param>
        /// <param name="fileName"></param>
        /// <param name="downloadFile"></param>
        protected void StartDownload(string fileName, string downloadFile)
        {
            //if (this.CanDownload(fileName, downloadFile))
            {
                this.Context.Response.Buffer = true;
                this.Context.Response.Clear();
                this.Context.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
                this.Context.Response.ContentType = "application/zip";
                this.Context.Response.WriteFile(downloadFile);
                this.Context.Response.End();
            }
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="codification"></param>
        protected void StartDownload(Codification codification, bool record=true)
        {
            if (this.CanDownload(codification))
            {
                if (record && LoginUser != null)
                {
                    string res = new DownloadLog().CreateNew(LoginUser, codification);
                    if (!string.IsNullOrEmpty(res))
                    {
                        throw new CustomException(res);
                    }
                }
                this.Context.Response.Buffer = true;
                this.Context.Response.Clear();
                this.Context.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", Server.UrlEncode(codification.FileName)));
                this.Context.Response.ContentType = "application/zip";
                this.Context.Response.WriteFile(codification.GetDownloadFileFullName());
                this.Context.Response.End();
            }
        }
        /// <summary>
        /// 获取下载法规的JS方法表达式
        /// </summary>
        /// <param name="codification"></param>
        /// <returns></returns>
        protected string GetDownloadJSString(Codification codification)
        {
            return string.Format("javascript:downloadFile(window,'{0}','{1}')", Base64.Encrypt(Base64.Encrypt(codification.ID.ToString())), this.BU);
        }

        protected string[] colors = new string[] { "cyan", "violet", "yellow", "red", "blue", "green", "gray", "moccasin" };
        protected string[] code = new string[]
        {
            char.ConvertFromUtf32(201),
            char.ConvertFromUtf32(202),
            char.ConvertFromUtf32(203),
            char.ConvertFromUtf32(204),
            char.ConvertFromUtf32(205),
            char.ConvertFromUtf32(206),
            char.ConvertFromUtf32(207),
        };
        protected void SetHighlight(string keyword)
        {
            g_pageInfo.SetInfo("highlight", keyword);
        }
        protected string GetHighlight()
        {
            object obj = g_pageInfo.GetInfo("highlight");
            return obj == null ? "" : obj.ToString();
        }

        /// <summary>
        /// 高亮指定的字符串
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        protected string Highlight(string input)
        {
            string[] keywords = this.GetHighlight().Split(" ".ToArray(), StringSplitOptions.RemoveEmptyEntries);
            int cnt = Math.Min(keywords.Length, colors.Length);
            string suffix = char.ConvertFromUtf32(199);
            if (input == "&nbsp;")
            {
                return "";
            }
            for (int i = 0; i < cnt; i++)
            {
                input = input.Replace(keywords[i], string.Format("{0}{1}{2}", char.ConvertFromUtf32(200 + i), keywords[i], suffix));
            }
            for (int i = 0; i < cnt; i++)
            {
                input = input.Replace(char.ConvertFromUtf32(200 + i), string.Format("<span style='font-weight:bolder; background-color:{0};'>", colors[i]));
            }
            return input.Replace(suffix, "</span>");
        }
        /// <summary>
        /// 高亮Grid一行中多个指定位置的cell的字段
        /// </summary>
        /// <param name="gridRow"></param>
        /// <param name="index"></param>
        protected void HighlightMulti(GridViewRow gridRow, params int[] index)
        {
            for (int i = 0; i < index.Length; i++)
            {
                int pos = index[i];
                if (gridRow.Cells.Count -1 < pos)
                {
                    continue;
                }
                gridRow.Cells[pos].Text = this.Highlight(gridRow.Cells[pos].Text);
            }
        }
        /// <summary>
        /// 在Grid中显示序号
        /// </summary>
        /// <param name="gridRow"></param>
        /// <param name="index"></param>
        protected void ShowSequenceNumber(GridViewRow gridRow, int index)
        {
            GridView gv = (GridView)gridRow.Parent.Parent;
            if (index <= gridRow.Cells.Count)
            {
                gridRow.Cells[index].Text = (gv.PageIndex * gv.PageSize + gridRow.RowIndex + 1).ToString();
            }
        }
        /// <summary>
        /// 格式化时间字符串
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="isDateTime">是否是日期时间</param>
        /// <returns></returns>
        protected string FormatDT(DateTime dt, bool isDateTime = false)
        {
            if (dt == DateTime.MaxValue)
            {
                return "";
            }
            return isDateTime ? dt.ToString("yyyy-MM-dd HH:mm:ss") : dt.ToString("yyyy-MM-dd");
        }

        /// <summary>
        /// 拆分分号分割的字符串成list
        /// </summary>
        /// <param name="strs"></param>
        /// <returns></returns>
        protected List<string> SplitStrS(string strs)
        {
            List<string> res = strs.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
            for (int i = 0; i < res.Count;i++ )
            {
                res[i] = res[i].Trim();
            }
            return res;
        }
        /// <summary>
        /// 将字符串列表组合成逗号分割的字符串
        /// </summary>
        /// <param name="strList"></param>
        /// <returns></returns>
        protected string CombineStrS(List<string> strList)
        {
            string res = "";
            for (int i = 0; i < strList.Count; i++)
            {
                res += strList[i] + " ; ";
            }
            res = res.TrimEnd("; ".ToCharArray());
            return res;
        }

        /// <summary>
        /// 存放在Session中的数据，使用字典结构，避免多开干扰
        /// </summary>
        protected Dictionary<string, object> SessionData
        {
            get
            {
                if (this.Session["SessionData"] == null)
                {
                    this.Session["SessionData"] = new Dictionary<string, object>();
                }
                return (Dictionary<string, object>)this.Session["SessionData"];
            }
        }
        protected void SetSessionData(string key, object val)
        {
            if (SessionData.ContainsKey(key))
            {
                SessionData[key] = val;
            }
            else
            {
                SessionData.Add(key, val);
            }
        }
        protected object GetSessionData(string key)
        {
            if (SessionData.ContainsKey(key))
            {
                return SessionData[key];
            }
            return null;
        }
        protected void RemoveSessionData(string key)
        {
            if (SessionData.ContainsKey(key))
            {
                SessionData.Remove(key);
            }
        }

        /// <summary>
        /// 失效列表
        /// </summary>
        /// <param name="pageID"></param>
        /// <param name="val"></param>
        /// <param name="remove"></param>
        /// <returns></returns>
        protected string InvalidList(string pageID, string val = null, bool remove = false)
        {
            string key = pageID + "InvalidList";
            if (remove)
            {
                this.RemoveSessionData(key);
                return "";
            }
            if (val != null)
            {
                this.SetSessionData(key, val);
            }
            object res = this.GetSessionData(key);
            return res == null ? "" : res.ToString();
        }
        /// <summary>
        /// 适用法规的公共信息
        /// </summary>
        /// <param name="pageID"></param>
        /// <param name="val"></param>
        /// <param name="remove"></param>
        /// <returns></returns>
        protected PublicFavoriteInfo PublicFavoriteInfo(string pageID, PublicFavoriteInfo val = null, bool remove = false)
        {
            string key = pageID + "InvalidList";
            if (remove)
            {
                this.RemoveSessionData(key);
                return null;
            }
            if (val != null)
            {
                this.SetSessionData(key, val);
                return val;
            }
            object res = this.GetSessionData(key);
            return res == null ? new PublicFavoriteInfo() : (PublicFavoriteInfo)res;
        }

        /// <summary>
        /// 页面实例ID
        /// </summary>
        protected string PageID
        {
            get
            {
                if (this.GetVSString("PageID") == "")
                {
                    this.SetVS("PageID", Guid.NewGuid().ToString().Substring(0, 8));
                }
                return this.GetVSString("PageID");
            }
            set { this.SetVS("PageID", value); }
        }

        protected void UploadFileIsvalid()
        {
            string uploadLength = System.Configuration.ConfigurationManager.AppSettings["UploadLength"];
            int length = this.GetInt(uploadLength);
            length = length == 0 ? 20 : length;

            //判断请求的内容长度是否超过了设置的字节数
            if (HttpContext.Current.Request.ContentLength - 300 > length * 1048576)
            {
                throw new CustomException(string.Format("最大上传文件大小为{0}M。", length));
            }
        }
    }
}